<?php
if (!is_array ($hash)) {
  $tmp = explode ('&', $hash);
  $hash = array ();
  
  foreach ($tmp as $t) {
    list ($key, $value) = explode ('=', $t);
    $hash[$key] = $value;
  }
}

$settings = variable_get ('paypal_settings', array ());

$MY_KEY_FILE        = $settings['private_key'];
$MY_CERT_FILE       = $settings['public_certificate'];
$PAYPAL_CERT_FILE   = $settings['paypal_certificate'];
$OPENSSL            = 'openssl'; // "/usr/bin/openssl";

if (!file_exists ($MY_KEY_FILE)) {
	$error_message[] = "MY_KEY_FILE $MY_KEY_FILE not found";
}

if (!file_exists ($MY_CERT_FILE)) {
	$error_message[] = "MY_CERT_FILE $MY_CERT_FILE not found";
}

if (!file_exists($PAYPAL_CERT_FILE)) {
	$error_message[] = "PAYPAL_CERT_FILE $PAYPAL_CERT_FILE not found";
}

if (is_array ($error_message)) {
	drupal_set_message ("Wrong system configuration. View system log for details.", 'error');
	watchdog ('standardpayment', implode ('<br />', $error_message));
}

/*if (!file_exists($OPENSSL)) {
	echo "ERROR: OPENSSL $OPENSSL not found\n";
}*/

//Assign Build Notation for PayPal Support
// $hash['bn']= 'StellarWebSolutions.PHP_EWP';

$openssl_cmd = 
  "$OPENSSL smime -sign -signer $MY_CERT_FILE -inkey $MY_KEY_FILE " .
  "-outform der -nodetach -binary | $OPENSSL smime -encrypt " .
  "-des3 -binary -outform pem $PAYPAL_CERT_FILE";

$descriptors = array (
  0 => array("pipe", "r"),
  1 => array("pipe", "w"),
);

$process = proc_open($openssl_cmd, $descriptors, $pipes);

if (is_resource ($process)) {
  foreach ($hash as $key => $value) {
    if ($value != "") {
      fwrite($pipes[0], "$key=$value\n");
    }
  }
  
  fflush($pipes[0]);
  fclose($pipes[0]);

  $output = "";
  while (!feof ($pipes[1])) {
    $output .= fgets ($pipes[1]);
  }
  
  fclose($pipes[1]); 
  $return_value = proc_close($process);
}
else {
  $output = 'ERROR';
}

